dsa

Java Expressions and Blocks

In this tutorial, you will learn about Java expressions, Java statements and Java blocks with the help of examples.

Like any language, Java lets you create variables, run tests on them and bundle them in nice packages. In programming terms, these concepts are defined as expressions, statements and blocks. This lesson will define each and provide Java code examples for each.



EXPRESSIONS

Expressions perform the work of a program. Among other things, expressions are used to compute and to assign values to variables and to help control the execution flow of a program. The job of an expression is twofold: to perform the computation indicated by the elements of the expression and to return a value that is the result of the computation.

For Example :


int score;
score = 95;

Here

score = 95
is an expression that return an int value.

Another Example :


if(num1==num2)
{
	System.out.println("Number 1 is equal to Number 2");
}

Here

num1==num2
is an expression that return a boolean value.

Here

"Number 1 is equal to Number 2"
is a String expression.

STATEMENTS

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

For Example :


//Expression
score = 95
//Statement
score = 95;

Here

score = 95
is an expression.

But after adding semicolon(;)Here

score = 95;
becomes a statement.

Java Blocks

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. Blocks are declared by using an open curly bracket ({) and a closing curly bracket (}).

The following example, BlockDemo, illustrates the use of blocks:


class BlockDemo 
{
     	public static void main(String[] args) 
	{
         	boolean condition = true;
          	if (condition) 
		{ 
			// begin block 1
               		System.out.println("Condition is true.");
          	} 	// end block one
          	else 
		{ 
			// begin block 2
               		System.out.println("Condition is false.");
          	} 	// end block 2
     	}
}